package objectives;

import geometry.Segment;
import geometry.Vertex;
import genotypes.Angles;
import geometry.IntersectionAlgorithm;
import java.util.Arrays;
import misc.Evaluation;
import geometry.Obstacle;

/**
 *
 * @author różański
 */
public class EuclidanObjective implements ObjectiveFunction {

    private double lengths[];
    private Vertex source, destination;
    private Obstacle obstacles[];
    private IntersectionAlgorithm algorithm;

    public EuclidanObjective(double lengths[], Obstacle[] obstacles,
            Vertex source, Vertex destination, IntersectionAlgorithm algorithm) {
        this.lengths = lengths;
        this.source = source;
        this.destination = destination;
        this.obstacles = obstacles;
        this.algorithm = algorithm;
    }

    // zakładam, że jest przynajmniej jedno ramię
    // ostatni odcinek to efektor - cel
    // póki co zwraca tylko odległość
    @Override
    public Evaluation evaluate(Angles angles) {
        int n = angles.getAngles().length;
        Segment segs[] = decode(angles);
        // segs[n] = new Segment(segs[n - 1].getEnd(), destination);
        Segment fromEndToDest = new Segment(segs[n - 1].getEnd(), destination);
       // System.out.println(segs[n - 1].getEnd());
        // todo: sprawdzić kolizje z przeszkodami
        boolean intersect = algorithm.checkIfIntersect(segs, obstacles);
        return new Evaluation(fromEndToDest.getLength(), intersect ? 1 : 0);

    }

    @Override
    public Segment[] decode(Angles angles) {
        int n = angles.getAngles().length;
        Segment[] segs = new Segment[n];
        segs[0] = new Segment(source, source.traverse(angles.getAngleAt(0), lengths[0]));
        for (int i = 1; i != n; ++i) {
            segs[i] = new Segment(segs[i - 1].getEnd(), segs[i - 1].getEnd().traverse(angles.getAngleAt(i), lengths[i]));
        }
        return segs;
    }
}
